package com.xbj.cloud.commons.exceptionHandler;

import com.xbj.cloud.commons.resp.ResultData;
import com.xbj.cloud.commons.resp.ReturnCodeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author: 观雾
 * @create: 2024-08-07
 * @description:
 **/

@RestControllerAdvice //是一个组合注解，由@ControllerAdvice、@ResponseBody组成，而@ControllerAdvice继承了@Component，
// 因此@RestControllerAdvice本质上是个Component，用于定义@ExceptionHandler，@InitBinder和@ModelAttribute方法，
// 适用于所有使用@RequestMapping方法
public class CommonExceptionHandler {
    private static final Logger LOG = LoggerFactory.getLogger(CommonExceptionHandler.class);

    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) //可以将某种异常映射为HTTP状态码
    @ExceptionHandler(Exception.class)
    public ResultData<String> exceptionHandle(Exception e) {
        LOG.error("全局异常处理,异常信息:" + e.getMessage() + "异常栈:" , e);
        String message;
        if (e instanceof MethodArgumentNotValidException) {
            //后端数据校验异常 validation
            MethodArgumentNotValidException exception = (MethodArgumentNotValidException) e;
            String field = exception.getBindingResult().getFieldError().getField();
            message = field+exception.getBindingResult().getFieldError().getDefaultMessage();

        }else {
            message = e.getMessage();
        }
        return ResultData.fail(ReturnCodeEnum.RC500.getCode(), message);


    }

}